//
//  DBHelper.m
//  ox
//
//  Created by 喻杰 on 2016/11/19.
//  Copyright © 2016年 fengge. All rights reserved.
//

#import "DBHelper.h"

#define ox_record @"create table if not exists ox_record (r_id integer PRIMARY KEY AUTOINCREMENT,content varchar,recorder varchar,record_time time,image_url varchar,img_width float,img_height float,lat float,lon float,poi_name varchar,address varchar)"


@implementation DBHelper

@synthesize dbPath,db;

@end


@implementation DBHelper (dbOpt)

-(instancetype)init{
    if(!dbPath){
        dbPath = [NSHomeDirectory()  stringByAppendingString:@"/Documents/ox.db"];
    }
    if(!db){
     db = [FMDatabase databaseWithPath:dbPath];
    }
    return self;
}


-(void)initDB{
    if([self openDB]){
        BOOL  flag =  [db executeUpdate:ox_record];
        if(flag){
            DDLogInfo(@"初始化表完成");
        }
    }else{
        DDLogInfo(@"数据库打开失败");
    }
}

-(BOOL) openDB{
    if(db){
        return [db open];
    }
    return NO;
}


-(BOOL) closeDB{
    if(db){
        return [db close];
    }
    return NO;
}

@end


@implementation DBHelper (dataOpt)

-(BOOL)excuteBy:(NSString *)sql values:(NSArray *)arr{
    if([self openDB]){
        DDLogInfo(@"%@,%@",sql,arr);
        NSError* err =nil;
        
        BOOL succeed = [db executeUpdate:sql values:arr error:&err];
        if(!succeed){
            DDLogError(@"%@",err);
        }
        [self closeDB];
        return succeed;
    }
    return NO;
}

-(NSMutableDictionary*) selectOneBy:(NSString*) sql params:(NSArray*)params{
    NSMutableDictionary* dic;
    NSMutableArray<NSMutableDictionary*>* arr = [self listBy:sql params:params resultNums:YES];
    if(arr.count>=1)
        dic= [arr objectAtIndex:0];
    return dic;
}
-(NSMutableArray<NSMutableDictionary*>*)listBy:(NSString*) sql params:(NSArray*)params{
    return [self listBy:sql params:params resultNums:NO];
}

-(NSMutableArray<NSMutableDictionary*>*)listBy:(NSString*) sql params:(NSArray*)params resultNums:(BOOL)isOne{
    NSMutableArray * arr  =[NSMutableArray array];
    if([self openDB]){
        DDLogInfo(@"sql=%@,params=%@",sql,params);
        NSError* err;
        FMResultSet * result =  [db executeQuery:sql values:params error:&err];
        if(err){
            DDLogError(@"%@",err);
            return arr;
        }
        while ([result next]) {
            NSMutableDictionary * res =[[NSMutableDictionary alloc]init];
            NSEnumerator<NSString*> *en = [result.columnNameToIndexMap keyEnumerator];
            NSString*key=nil;
            while ((key =[en nextObject])!=nil) {
                [res setValue:[result objectForColumnName:key] forKey:key ];
            }
            [arr addObject:res];
            if(isOne){
                break;
            }
        }
        [self closeDB];
    }
    return arr;
}




@end
